package com.example.demo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

@WebServlet(name = "userloginServlet", value = "/userloginServlet")
public class userloginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username =request.getParameter("txtName");
        String userpwd =request.getParameter("txtUserpassword");

        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        if (username.equals(userpwd))
        {
            response.getWriter().println("登陆成功");
        }
        else {
            response.getWriter().println("登陆失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        //1、查看登陆参数 用户名和密码
        String username = request.getParameter("txtName");
        String userpassword = request.getParameter("txtUserpassword");
        // 数据库连接URL，格式为：jdbc:mysql://host:port/databaseName
        String url = "jdbc:mysql://localhost:3306/user";
        // 数据库用户名
        String user = "root";
        // 数据库密码
        String password = "12345";
        int result =0;
        try {
            // 加载MySQL JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection conn = DriverManager.getConnection(url, user, password);
            // 创建Statement对象执行SQL语句
            Statement stmt = conn.createStatement();
            // 执行查询并获取结果
            ResultSet rs = stmt.executeQuery("select count(*) as a  from users2 where userNo='"+username+"' and userPwd='"+userpassword+"'");
            // 处理结果
            if (rs.next()) {
                result  = rs.getInt("a");
            }
            // 关闭结果集、Statement和连接
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.执行登陆逻辑
        //3.返回登陆结果
        if (result == 1 )
            response.sendRedirect("userindex.html");
        else
            response.getWriter().println("登陆失败.");
        // System.out.println("xxxxxxxxxxxxxxxxxx do post");
    }
}
